﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using AutoMapper;
using H2.NET.Business.Core;
using H2.NET.Common;
using H2.NET.Data.Common;
using H2.NET.Web.Workflow.Models;
using H2.NET.Web.Workflow.Services;
using Ultimus.OC;
using log4net;
using System.Reflection;

namespace H2.NET.Web.Index
{
    public partial class Logon : System.Web.UI.Page
    {
        [SessionType]
        public clsCommon clsCmm = new clsCommon();

        [SessionType]
        public string SessionUser = "";


        #region 事件 页面 加载
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                Response.Buffer = true;
                Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
                Response.Expires = 0;
                Response.CacheControl = "no-cache";

                //第一次加载页面时初始化
                if (!Page.IsPostBack)
                {
                    txtUserName.Attributes.Add("onkeydown", "javascript:document.getElementById('txtPassword').value = '';");

                    //控件文本初始化
                    btnLogin.Text = clsCmm.getTextValue("frm_logon_btnLogin");

                    //根据 Cookies 中保存的语言设置来初始化环境语言
                    if (Request.Cookies["comm_language"] != null)
                    {
                        clsCmm.comm_language = Request.Cookies["comm_language"].Value;
                    }
                    else
                    {
                        clsCmm.comm_language = "en-us";
                        Util.SetCookies("comm_language", "zh-cn", DateTime.MaxValue);
                    }

                    drpLang.SelectedValue = clsCmm.comm_language;

                    //根据 Cookies 中保存的用户账号初始化用户名输入框
                    if (Request.Cookies["comm_username"] != null)
                    {
                        txtUserName.Text = Request.Cookies["comm_username"].Value;
                        if (Request.Cookies[txtUserName.Text.Trim()] != null)
                        {
                            txtPassword.Attributes.Add("value", Request.Cookies[txtUserName.Text.Trim()].Value);
                            pwdCheck.Checked = true;
                        }
                    }

                    //根据 Cookies 中保存的域信息来初始化域下拉框
                    string strDomain = "";
                    if (Request.Cookies["comm_domain"] != null)
                    {
                        strDomain = Request.Cookies["comm_domain"].Value;
                    }

                    //从服务器上取得所有域信息
                    string[] str_domains = Util.AppSettings("domain").Split(new char[2] { '}', '{' }, StringSplitOptions.RemoveEmptyEntries);
                    if (str_domains != null)
                    {
                        int intIndex = 0;
                        for (int i = 0; i < str_domains.Length; i++)
                        {
                            ListItem itmDomain = new ListItem();
                            itmDomain.Text = str_domains[i].Trim();
                            itmDomain.Value = str_domains[i].Trim();
                            drpDomain.Items.Add(itmDomain);

                            //判断域信息是否相同
                            if (strDomain == itmDomain.Value)
                            {
                                drpDomain.SelectedIndex = intIndex;
                            }

                            intIndex++;
                        }
                    }

                    //中英文按钮文字初始化
                    if (clsCmm.comm_language == "en-us")
                    {
                        lbtnLang.Text = "中文";
                    }
                    else
                    {
                        lbtnLang.Text = "English";
                    }

                    //设置输入焦点
                    //txtUserName.Focus();
                    string scp = "document.getElementById( '{0}').focus(); ";
                    txtUserName.Page.ClientScript.RegisterStartupScript(txtUserName.GetType(), "setfocus ", string.Format(scp, txtUserName.ClientID), true);
                }
            }
            catch (Exception ee)
            {
                TaskDB.Log("", false, "调用 logon.aspx 页面 Page_Load 事件出错：" + ee.Message);
            }
        }
        #endregion

        #region 事件 单击 Login 按钮
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                bool isValidate = false;
                lblErrInfomation.Text = "";

                //清空以往的登陆信息
                clsCmm.Logout();

                if (txtUserName.Text.IndexOf('@') > 0)
                {
                    txtUserName.Text = txtUserName.Text.Substring(0, txtUserName.Text.IndexOf('@'));
                }

                txtUserName.Text = txtUserName.Text.Trim().ToLower();

                if (txtUserName.Text == "")
                {
                    lblErrInfomation.Text = "Please enter your username.";
                    txtUserName.Focus();
                    return;
                }

                //从数据库里取得账号
                string strSQL = "";
                string strUserName = "";
                DataTable dt_tmp = new DataTable();
                strSQL = "select rtrim(name) as name from jobs where lower(name)=lower('" + drpDomain.SelectedItem.Value + "/" + txtUserName.Text.Trim() + "') or lower(fullname)=lower('" + txtUserName.Text.Trim() + "')";
                clsCmm.clsDB.Storage("bpmDB");
                dt_tmp = clsCmm.clsDB.Query(strSQL);

                //验证是否合法用户
                OrgChart oc = new OrgChart();

                //是否取管理员默认密码
                if (dt_tmp.Rows.Count > 0)
                {
                    strUserName = dt_tmp.Rows[0]["name"].ToString();
                    var aryUserName = strUserName.Split('/');
                    if (aryUserName.Length > 1)
                    {
                        strUserName = aryUserName[1];
                    }

                    string UserName = drpDomain.SelectedItem.Value + "/" + (strUserName == "" ? txtUserName.Text.Trim() : strUserName);
                    //string Password = txtPassword.Text.Trim();
                    string Password = "123456";

                    string appSetting_Password = Util.AppSettings("password");
                    if ((!string.IsNullOrEmpty(appSetting_Password) && Password == Util.Decrypt(appSetting_Password) &&
                         !string.IsNullOrEmpty(txtUserName.Text))
                        || oc.VerifyUser(UserName, Password))
                    {
                        isValidate = true;
                    }
                }

                //如果验证通过的情况
                if (isValidate)
                {
                    clsCmm.comm_domain = drpDomain.SelectedItem.Value;
                    clsCmm.comm_username = clsCmm.comm_domain + "/" + (strUserName == "" ? txtUserName.Text.Trim() : strUserName);
                    clsCmm.comm_short_username = (strUserName == "" ? txtUserName.Text.Trim() : strUserName);

                    Util.SetCookies("comm_username", clsCmm.comm_short_username, DateTime.MaxValue);
                    Util.SetCookies("UserName", Util.Encrypt(clsCmm.comm_username), DateTime.MaxValue);
                    if (Request.Cookies[txtUserName.Text.Trim()] == null && pwdCheck.Checked)
                    {
                        Util.SetCookies(txtUserName.Text.Trim(), txtPassword.Text.Trim(), DateTime.Now.AddDays(7));
                    }
                    else if (Request.Cookies[txtUserName.Text.Trim()] != null && !pwdCheck.Checked)
                    {
                        //Request.Cookies[txtUserName.Text.Trim()].Expires = DateTime.Now.AddYears(-10);
                        //Request.Cookies.Remove(txtUserName.Text.Trim());
                        Util.SetCookies(txtUserName.Text.Trim(), txtPassword.Text.Trim(), DateTime.Now.AddDays(-7));
                    }
                    Util.SetCookies("comm_domain", clsCmm.comm_domain, DateTime.MaxValue);

                    //取得用户扩展信息
                    User ocUser = new User();
                    UserPreferences up = new UserPreferences();
                    oc.FindUser(clsCmm.comm_username, "", 0, out ocUser);

                    //在当前用户存在的情况下
                    if (ocUser != null)
                    {
                        clsCmm.comm_userfullname = ocUser.strUserFullName;          //用户名
                        clsCmm.comm_userdepartment = ocUser.strDepartmentName;        //用户所属的部门    
                        clsCmm.comm_job = ocUser.strJobFunction;
                        try
                        {
                            ocUser.GetUserPrefs(out up);
                            clsCmm.comm_mail = up.strEmail;
                        }
                        catch (Exception)
                        { }
                    }

                    SessionUser = clsCmm.comm_username + "~" + clsCmm.comm_userfullname + "~" + clsCmm.comm_userdepartment + "~" + clsCmm.comm_job + "~" + clsCmm.comm_language + "~" + clsCmm.comm_mail;

                    #region 取得报表数据相关
                    string str_department = "";
                    string str_jobfunction = "";

                    #region 部门取得
                    //部门取得
                    strSQL = "select distinct name from departments where id in(select deptid from jobs where lower(name) = lower('" + clsCmm.comm_username + "'))";
                    clsCmm.clsDB.Storage("bpmDB");
                    dt_tmp = clsCmm.clsDB.Query(strSQL);

                    //如果存在返回值的情况
                    str_department = "";
                    for (int i = 0; i < dt_tmp.Rows.Count; i++)
                    {
                        if (i == dt_tmp.Rows.Count - 1)
                        {
                            str_department += dt_tmp.Rows[i]["name"].ToString().Trim();
                        }
                        else
                        {
                            str_department += dt_tmp.Rows[i]["name"].ToString().Trim() + "','";
                        }
                    }
                    #endregion

                    #region 角色取得
                    //角色取得
                    strSQL = "select distinct name, jobfunction";
                    strSQL += "  from (select rtrim(b.name) as name, rtrim(a.jobfunction) as jobfunction";
                    strSQL += "          from (select deptid, jobfunction";
                    strSQL += "                  from jobs";
                    strSQL += "                 where id in (select supervisorid";
                    strSQL += "                                from jobs a";
                    strSQL += "                               where lower(a.name) = lower('" + clsCmm.comm_username + "')";
                    strSQL += "                                 and jobtype = 64)) a,";
                    strSQL += "               departments b";
                    strSQL += "         where a.deptid = b.id";
                    strSQL += "        union";
                    strSQL += "        select rtrim(b.name) as name, rtrim(a.jobfunction) as jobfunction";
                    strSQL += "          from jobs a, departments b";
                    strSQL += "         where a.deptid = b.id";
                    strSQL += "           and lower(a.name) = lower('" + clsCmm.comm_username + "')";
                    strSQL += "           and jobtype <> 64) t_xxxx_tmp";

                    clsCmm.clsDB.Storage("bpmDB");
                    dt_tmp = clsCmm.clsDB.Query(strSQL);

                    //如果存在返回值的情况
                    str_jobfunction = "";
                    for (int i = 0; i < dt_tmp.Rows.Count; i++)
                    {
                        if (i == dt_tmp.Rows.Count - 1)
                        {
                            str_jobfunction += dt_tmp.Rows[i]["name"].ToString().Trim() + @"\" + dt_tmp.Rows[i]["jobfunction"].ToString().Trim();
                        }
                        else
                        {
                            str_jobfunction += dt_tmp.Rows[i]["name"].ToString().Trim() + @"\" + dt_tmp.Rows[i]["jobfunction"].ToString().Trim() + "','";
                        }

                    }
                    #endregion

                    //设置报表参数相关
                    clsCmm.clsRpt.set_rpt_para_value("{current_dept}", str_department);
                    clsCmm.clsRpt.set_rpt_para_value("{current_job}", str_jobfunction);
                    clsCmm.clsRpt.set_rpt_para_value("{current_user}", clsCmm.comm_username);
                    clsCmm.clsRpt.set_rpt_para_value("{current_userfullname}", clsCmm.comm_userfullname);

                    #region 判断是否为管理员
                    strSQL = " select distinct a.grp_m_fk_grp_no";
                    strSQL += "   from t_group_member a";
                    strSQL += "  where grp_m_fk_grp_no='SYS-0001'";
                    strSQL += "    and (a.grp_m_type_v in ('[current_dept]', '[all_dept]', '[current_user]','[all_user]', '[current_job]', '[all_job]')";
                    strSQL += "     or (a.grp_m_type='1' and a.grp_m_type_v in ('" + clsCmm.clsRpt.get_rpt_para_value("{current_dept}") + "'))";
                    strSQL += "     or (a.grp_m_type='2' and a.grp_m_type_v in ('" + clsCmm.clsRpt.get_rpt_para_value("{current_user}") + "'))";
                    strSQL += "     or (a.grp_m_type='3' and a.grp_m_type_v in ('" + clsCmm.clsRpt.get_rpt_para_value("{current_job}") + "')))";

                    clsCmm.clsDB.Storage("oleDB");
                    dt_tmp = clsCmm.clsDB.Query(strSQL);
                    if (dt_tmp.Rows.Count > 0)
                    {
                        clsCmm.comm_is_administrator = true;
                    }
                    else
                    {
                        clsCmm.comm_is_administrator = false;
                    }
                    #endregion

                    #endregion

                    //转入主界面
                    Response.Redirect("index.aspx", false);
                }
                else
                {
                    lblErrInfomation.Text = dt_tmp.Rows.Count <= 0 ? Util.AppSettings("err_logon") : clsCmm.getTextValue("frm_logon_pwd_err");
                }
            }
            catch (Exception ee)
            {
                TaskDB.Log("", false, "调用 logon.aspx 页面 Login_Click 事件出错：" + ee.Message);
            }
        }
        #endregion

        #region 事件 单击 Language 按钮
        protected void lbtnLang_Click(object sender, EventArgs e)
        {
            try
            {
                //设置 Cookies 中的语言
                if (lbtnLang.Text == "English")
                {
                    clsCmm.comm_language = "en-us";
                    lbtnLang.Text = "中文";
                    Util.SetCookies("comm_language", "en-us", DateTime.MaxValue);
                }
                else
                {
                    clsCmm.comm_language = "zh-cn";
                    lbtnLang.Text = "English";
                    Util.SetCookies("comm_language", "zh-cn", DateTime.MaxValue);
                }

                //设置输入焦点
                //txtUserName.Focus();
                string scp = "document.getElementById( '{0}').focus(); ";
                txtUserName.Page.ClientScript.RegisterStartupScript(txtUserName.GetType(), "setfocus ", string.Format(scp, txtUserName.ClientID), true);

                //控件文本初始化
                btnLogin.Text = clsCmm.getTextValue("frm_logon_btnLogin");
            }
            catch (Exception ee)
            {
                TaskDB.Log("", false, "调用 logon.aspx 页面 Lang_Click 事件出错：" + ee.Message);
            }
        }
        #endregion

        #region 事件 多语言
        protected void drpLang_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                clsCmm.comm_language = drpLang.SelectedValue;
                Util.SetCookies("comm_language", drpLang.SelectedValue, DateTime.MaxValue);

                btnLogin.Text = clsCmm.getTextValue("frm_logon_btnLogin");
            }
            catch (Exception)
            {
            }
        }
        #endregion
    }
}
